import React,{PureComponent} from 'react';
import {connect} from 'react-redux';
import {HomeWrapper, HomeLeft, HomeRight, BackTop} from './style'
import {actionCreator} from './store'
import List from './components/List'
import Recommend from './components/Recommend'
import Topic from './components/Topic'
import Writer from './components/Writer'


// PureComponent优化组件性能。必须和immutable.js一起用，不用immutable坑多
class Home extends PureComponent{
  render() {
    return (
      <HomeWrapper>
        <HomeLeft>
          <img src="https://upload.jianshu.io/admin_banners/web_images/4816/c4a3e25c0e339848d4f04a264623666f16fd3602.png?imageMogr2/auto-orient/strip|imageView2/1/w/1250/h/540"
               alt="" className="banner-img"
          />
          <Topic />
          <List />
        </HomeLeft>
        <HomeRight>
          <Recommend />
          <Writer />
        </HomeRight>
        {
          this.props.showBack ? <BackTop onClick={this.handleBack}>返回</BackTop> : null
        }
      </HomeWrapper>
    )
  }

  handleBack() {
    document.documentElement.scrollTop = 0
  }

  componentDidMount() {
    this.props.handleHomeAjax();
    window.addEventListener('scroll', this.props.handleScroll)
  }

  componentWillUnmount() {
    window.removeEventListener('scroll', this.props.handleScroll)
  }
}

const mapDispatchToProps = (dispatch) => {
  return {
    handleHomeAjax() {
      dispatch(actionCreator.changeHomeAction());
    },
    handleScroll() {
      if (document.documentElement.scrollTop > 100) {
        dispatch(actionCreator.showBack(true))
      } else {
        dispatch(actionCreator.showBack(false))
      }
    }
  }
};

const mapStateToProps = (state) => ({
  showBack: state.getIn(['home', 'showBack'])
});

export default connect(mapStateToProps, mapDispatchToProps)(Home);